from rest_framework import serializers

from hlq import models


class ArticleSerializers(serializers.ModelSerializer):
    content = serializers.CharField(source='articledetail.content')

    class Meta:
        model = models.Article
        exclude = ['author', ]

    def create(self, validated_data):
        # ModelSerializer类中的create()方法，不支持我们自定义数据结构。
        # 所以我们要使用自定义结构，必须自己重写create()方法：
        print("validated_data:", validated_data)

        # 添加book表中的新书记录
        article = models.Article.objects.create(category=validated_data['category'], title=validated_data['title'],
                                                image=validated_data['image'], summary=validated_data['summary'],
                                                author=models.User_info.objects.first()
                                                )
        # article.author.add(models.User_info.objects.first())

        # title=validated_data['title'], price=validated_data['price'],
        #                        pub_date=validated_data['pub_date'], publish_id=validated_data['publish']['pk'])
        # # 添加多对多表中的记录
        # book.authors.add(*validated_data['authors'])

        return article


class ArticleDetailSerializers(serializers.ModelSerializer):
    content = serializers.CharField(source='articledetail.content')

    class Meta:
        model = models.ArticleDetail
        # fields = '__all__'
        exclude = ['article', ]


class ArticleListSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.Article
        fields = '__all__'
        # exclude = ['article', ]


class PageArticleSerializers(serializers.ModelSerializer):
    content = serializers.CharField(source='articledetail.content')
    # 此处不知道为何需要天author，有可能是因为author的ForeignKey指向了user_info表
    author = serializers.CharField(source='author.user_name')
    category = serializers.CharField(source='get_category_display')

    class Meta:
        model = models.Article
        fields = '__all__'


class CommentSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.Comment
        fields = '__all__'


class PostCommentSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.Comment
        # fields = '__all__'
        exclude = ['user']
